package httpserver

import (
	"io/ioutil"
	"net/http"
	"prize/go-common/logger"
)

type ResponseWriter interface {
	http.ResponseWriter
	http.Hijacker
	http.Flusher
	http.CloseNotifier

	Status() int

	Size() int

	WriteString(string) (int, error)

	Written() bool

	WriteHeaderNow()

	Pusher() http.Pusher
}

type RequestCtx struct {
	Request *http.Request
	Writer  ResponseWriter
}

func (c *RequestCtx) GetQueryParam(key string) string {
	paramMap := c.Request.URL.Query()
	if val, ok := paramMap[key]; ok && len(val) > 0 {
		return val[0]
	}
	return ""
}

func (c *RequestCtx) GetPostParam(key string) string {
	err := c.Request.ParseForm()
	if err != nil {
		return ""
	}
	return c.Request.FormValue(key)
}

func (c *RequestCtx) GetBody() string {
	ret, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		logger.Error("GetBody ReadAll 读取失败:", err)
		return ""
	}

	defer func() {
		err := c.Request.Body.Close()
		if err != nil {
			logger.Error("请求关闭失败", err)
		}
	}()

	return string(ret)
}

func (c *RequestCtx) Header() http.Header {
	return c.Request.Header
}
